package com.example.okhttp.util

import android.util.Base64
import java.nio.charset.StandardCharsets
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

object CryptoUtils {
    private const val AES_ALGORITHM = "AES/CBC/PKCS7Padding"

    // 获取密钥
    private fun getSecretKey(key: String): SecretKey {
        val keyBytes = key.toByteArray(StandardCharsets.UTF_8)
        return SecretKeySpec(keyBytes, "AES")
    }

    // 获取初始化向量
    private fun getIV(iv: String): ByteArray = iv.toByteArray(StandardCharsets.UTF_8)

    // AES加密
    fun encrypt(data: String, key: String, iv: String): String {
        val cipher = Cipher.getInstance(AES_ALGORITHM)
        val secretKey = getSecretKey(key)
        val ivParameterSpec = IvParameterSpec(getIV(iv))
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec)

        val encryptedBytes = cipher.doFinal(data.toByteArray(StandardCharsets.UTF_8))
        return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP)
    }

    // AES解密
    fun decrypt(encryptedData: String, key: String, iv: String): String {
        val encryptedBytes = Base64.decode(encryptedData, Base64.NO_WRAP)
        val cipher = Cipher.getInstance(AES_ALGORITHM)
        val secretKey = getSecretKey(key)
        val ivParameterSpec = IvParameterSpec(getIV(iv))
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec)

        val decryptedBytes = cipher.doFinal(encryptedBytes)
        return String(decryptedBytes, StandardCharsets.UTF_8)
    }
}